/*******************************************************************************************
 *      @name   bemfa.c
 *      @brief  这是在linux系统下的使用gethostbyname对巴法云域名进行解析的代码案例
 *      @date   2025/02/21
 *      @author cecelmx@126.com 
 *      @note
 *              1.巴法云支持TCP协议，TCP协议的端口是8344，域名是bemfa.com
 * 
 *      @version  xx.xx.xx   主版本号.次版本号.修正版本号
 * 
 *      CopyRight (c)   2024-2025   Your Name     All Right Reserved
 * 
 * ****************************************************************************************/

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/udp.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <netdb.h>

#define  BUFSIZE 512

#define  UID   "124c27fd799448be89c420c70b53a80e"  //用户密钥

#define  TOPIC "led002"         //主题名称

int main(int argc,char **argv)
{

    char recvbuf[BUFSIZE] ={0};

    //1.创建TCP套接字
    int tcp_socket = socket(AF_INET, SOCK_STREAM, 0); 
    if(-1 == tcp_socket)
    {
        fprintf(stderr,"create tcp socket error,%s\n",strerror(errno));
        exit(-1);
    }
    
    //2.向服务器发起连接请求
    struct sockaddr_in dest ={0};                   //IPv4地址格式的实例
    dest.sin_family = AF_INET;                      //IPv4协议族
    dest.sin_port   = htons(8344);                  //目标端口，需要转换为网络字节序
    dest.sin_addr.s_addr = inet_addr("119.91.109.180");  //目标地址，需要转换为网络字节序

    if(-1 == connect(tcp_socket,(struct sockaddr *)&dest,sizeof(dest)))
    {
        fprintf(stderr,"connect error,%s\n",strerror(errno));
        exit(-2);
    }

    printf("connect ok\n");

    //3.连接成功后，可以订阅服务器的主题，需要构造消息内容
    char msgbuf[BUFSIZE] ={0};
    sprintf(msgbuf,"cmd=1&uid=%s&topic=%s\r\n",UID,TOPIC);

    send(tcp_socket,msgbuf,strlen(msgbuf),0); //向巴法云服务器发送订阅主题的消息

    printf("send ok\n");

    //接收服务器下发的订阅状态
    recv(tcp_socket,recvbuf,sizeof(recvbuf),0); //读取数据，默认会阻塞
    printf("recv data from bemfa server is %s\n",recvbuf);
    memset(recvbuf,0,BUFSIZE);

    while(1)
    {
        //发布消息
        memset(msgbuf,0,BUFSIZE);
        sprintf(msgbuf,"cmd=2&uid=%s&topic=%s&msg=%s\r\n",UID,TOPIC,"off");
        send(tcp_socket,msgbuf,strlen(msgbuf),0); //向巴法云服务器发送订阅主题的消息

        sleep(5);
    }
    

    return 0;
}

